package com.wanchuang.qhbb.web.manager;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.RequiresApi;

import com.wanchuang.qhbb.base.MainApplication;
import com.wanchuang.qhbb.utils.LogUtil;
import com.wanchuang.qhbb.web.ui.WebViewActivity;

public class WebViewClientUtil extends WebViewClient {
    private final WebClientLoadListener loadListener;
    Activity activity;

    private boolean isError;

    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
        Log.e("imageUrl",url);
    }

    public WebViewClientUtil(Activity activity, WebClientLoadListener loadListener) {
        this.activity = activity;
        this.loadListener = loadListener;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.startsWith(MainApplication.getServiceHost())){ //非本站域名 不跳转新的页面
            WebViewActivity.startActivity(activity,url);
            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }




    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        isError=false;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        if(error.getErrorCode()!=-2){
            isError = true;
        }
        LogUtil.e("wang",error.getErrorCode()+" ::"+error.getDescription());
    }

    /**
     * 界面加载完后回调
     * @param view
     * @param url
     */
    @Override
    public void onPageFinished(WebView view, String url) {
        String title = view.getTitle(); // 获取网页标题
        loadListener.loadFinished(title,isError);
        super.onPageFinished(view, url);
    }
    public interface WebClientLoadListener{
        void loadFinished(String title, boolean isError);
    }

}